<script setup lang="ts">
import type { CreatePlottingSceneDTO } from '#/api/plotting/dto';

import { nextTick, onBeforeUnmount, onMounted } from 'vue';

import { StorageManager } from '@vben-core/shared/cache';

import { ElMessage } from 'element-plus';

import { PlottingSceneApi } from '#/api';
import Header from '#/components/plotting/header.vue';
import LeftBar from '#/components/plotting/left-bar.vue';
import Map from '#/components/plotting/map.vue';
import PlotSetting from '#/components/plotting/plotting-setting.vue';
import { usePlottingMapStore } from '#/store/modules/mapStore';
import plottingSceneManager from '#/store/modules/plotting-scene-manager';
import { cryptoUtil, dataURLtoFile, html2canvasTool } from '#/utils';
import { formatSML, parseSMLString } from '#/utils/plotting-utils';

const mapStore = usePlottingMapStore();

const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});

async function getCurrentSceneThumbnail() {
  const target = document.querySelector('#map') as HTMLElement;
  if (target) {
    await nextTick(); // 等 DOM 渲染完成
    const sceneImgCanvas = await html2canvasTool(target);
    return sceneImgCanvas.toDataURL('image/png');
  } else {
    ElMessage.warning('场景图片生成失败，请刷新页面重试');
    return false;
  }
}

const handleSceneSave = async () => {
  const sml = formatSML();
  const serializer = new XMLSerializer();
  const smlString = serializer.serializeToString(sml);
  const sceneImg: boolean | string = await getCurrentSceneThumbnail();
  const sceneImgFile = dataURLtoFile(sceneImg, cryptoUtil.Encrypt(Date.now()));
  const dto: CreatePlottingSceneDTO = {
    name: '标绘场景3',
    smlString,
    userId: storageManager.getItem<string>('userId') as string,
    thumbnail: sceneImgFile,
  };
  const currentScene = plottingSceneManager.getScene();
  if (currentScene!.id === '') {
    const res = await PlottingSceneApi.createPlottingScene(dto);
    if (res) {
      plottingSceneManager.setScene(res);
      ElMessage.success('场景保存成功！');
    }
  } else {
    const res = await PlottingSceneApi.updatePlottingScene(
      currentScene!.id,
      dto,
    );
    if (res) {
      plottingSceneManager.setScene(res);
      ElMessage.success('场景保存成功！');
    }
  }
};
function waitForSceneReady(): Promise<void> {
  return new Promise((resolve) => {
    const checkReady = () => {
      const scene = plottingSceneManager.getScene();
      if (scene && scene.id !== '') {
        resolve();
      } else {
        setTimeout(checkReady, 50); // 每50ms检查一次
      }
    };
    checkReady();
  });
}

onMounted(() => {
  window.eventBus.on('parseSML', async () => {
    try {
      await waitForSceneReady();
      const scene = plottingSceneManager.getScene();
      if (scene && scene.smlString) {
        parseSMLString(scene.smlString);
      } else {
        console.warn('smlString未准备好');
      }
    } catch (error) {
      console.warn(error);
    }
  });
});

onBeforeUnmount(() => {
  window.eventBus.off('parseSML');
  plottingSceneManager.clear();
});
</script>

<template>
  <div class="plotting-container">
    <div class="map-container">
      <Map />
    </div>

    <div class="header">
      <Header @save-scene="handleSceneSave()" />
    </div>
    <div class="left-bar">
      <LeftBar />
    </div>
    <div v-if="mapStore.selectedNode.length > 0" class="plot-settings">
      <PlotSetting />
    </div>
  </div>
</template>

<style lang="scss">
:where(.css-dev-only-do-not-override-1p3hq3p).ant-tabs .ant-tabs-tab-btn {
  color: white;
}

@mixin glass-effect(
  $background-color: rgba(255, 255, 255, 0.1),
  $blur: 10px,
  $border-radius: 15px
) {
  background: $background-color;
  /* stylelint-disable-next-line declaration-block-no-duplicate-properties */
  backdrop-filter: blur($blur);
  backdrop-filter: blur($blur); // 兼容 Webkit 内核
  border-radius: $border-radius;
}

.plotting-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.header {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 6%;
  // background: rgb(35, 35, 35);
}

.map-container {
  width: 100vw;
  height: 100%;
}

.left-bar {
  // height: 100%;
  position: absolute;
  top: 6%;
  left: 0;
  // top: 0;
  width: 16%;
  height: 94%;
  background: rgb(51 59 73);
}

.plot-settings {
  // height: 100%;
  position: absolute;
  top: 6%;
  left: 16%;
  // top: 0;
  width: 14%;
  height: 94%;
  background: rgb(51 59 73);
  border-left: 3px solid rgb(39 39 39);
}
</style>
